package com.atguigu.tingshu.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.context.OrderHandlerInterceptorContext;
import com.atguigu.tingshu.order.context.OrderTradeStrategyContext;
import com.atguigu.tingshu.order.enums.OrderStatusNameEnum;
import com.atguigu.tingshu.order.enums.PayWayEnumNameEnum;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {


    private final OrderInfoMapper orderInfoMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final KafkaService kafkaService;
    @Autowired
    public OrderInfoServiceImpl(OrderInfoMapper orderInfoMapper, OrderDetailMapper orderDetailMapper, KafkaService kafkaService) {
        this.orderInfoMapper = orderInfoMapper;
        this.orderDetailMapper = orderDetailMapper;
        this.kafkaService = kafkaService;
    }

    /**
     * @description: 确认订单
     * @author Petrichor
     * @date 2024/1/5 20:18
     * @param tradeVo 订单确认对象
     * @return orderInfoVo 订单对象
     **/
    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {
        // 付款项目类型: 1001-专辑 1002-声音 1003-vip会员
        String itemType = tradeVo.getItemType();
        // 根据付款项目的取值获取对应的策略实现类对象
        OrderTradeStrategy orderTradeStrategy = OrderTradeStrategyContext.getOrderTradeStrategy(itemType);
        OrderInfoVo trade = orderTradeStrategy.trade(tradeVo);
        return trade;
    }
    /**
     * @description: 提交订单
     * @author Petrichor
     * @date 2024/1/7 23:08
     * @param orderInfoVo 订单对象
     * @return 订单id
     **/
    @Override
    public String submitOrder(OrderInfoVo orderInfoVo) {
        OrderInfoVo result = OrderHandlerInterceptorContext.entry(orderInfoVo);
        return result.getTradeNo();
    }
    /**
     * @description: 根据订单id 取消订单
     * @author Petrichor
     * @date 2024/1/8 18:19
     * @param orderNo 订单号
     * @return
     **/
    @Override
    public void orderCancel(String orderNo) {
        // 构建查询条件  根据 订单号 查询 订单信息
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo , orderNo) ;
        OrderInfo orderInfo = this.getOne(lambdaQueryWrapper);
        // 获取订单状态
        String orderStatus = orderInfo.getOrderStatus();
        // 如果是0901 未支付 则进入
        if(SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
            // 使用乐观锁进行修改，防止在判断完毕以后，在修改之前用户对订单支付成功了
            lambdaQueryWrapper.eq(OrderInfo::getOrderStatus , SystemConstant.ORDER_STATUS_UNPAID) ;
            this.update(orderInfo , lambdaQueryWrapper) ;
        }
    }
    /**
     * @description: 保存订单数据后的 后续操作 保存交易信息(保存购买信息user_paid_album、user_paid_track、user_vip_service)
     * @author Petrichor
     * @date 2024/1/8 21:24
     * @param orderNo 订单编号
     * @return NULL
     **/
    @Override
    public void orderPaySuccess(String orderNo) {
        // 更改订单状态为已支付
        this.updateOrderStatus(orderNo,SystemConstant.ORDER_STATUS_PAID);
        // 获取用户id
        Long userId = AuthContextHolder.getUserId();
        // 根据订单的编号查询订单数据， 查询订单的明细
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        // 获取明细的id的集合
        List<Long> idList = orderInfo.getOrderDetailList().stream()
                .map(orderDetail -> orderDetail.getItemId())
                .collect(Collectors.toList());
        // 保存交易信息(保存购买信息 user_paid_album、user_paid_track、user_vip_service)
        // 让order微服务和user微服务进行通讯，可以使用kafka
        // 要发送的消息内容：orderNo、user_id 、明细列表的id
        UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        userPaidRecordVo.setOrderNo(orderNo);
        userPaidRecordVo.setUserId(userId);
        userPaidRecordVo.setItemType(orderInfo.getItemType());
        userPaidRecordVo.setItemIdList(idList);

        kafkaService.sendMsg(KafkaConstant.QUEUE_USER_PAY_RECORD, JSON.toJSONString(userPaidRecordVo));
    }

    /**
     * @description: 根据订单的编号查询订单数据， 查询订单的明细
     * @author Petrichor
     * @date 2024/1/8 22:39
     * @param orderNo 订单编号
     * @return 订单信息 + 明细
    **/
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {

        // 根据订单的编号查询订单的数据
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo , orderNo) ;
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);

        // 根据订单的id查询订单名称
        Long orderId = orderInfo.getId();
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId , orderId) ;
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
        orderInfo.setOrderDetailList(orderDetails);
        // 设置 orderStatusName 订单状态名称
        orderInfo.setOrderStatusName(OrderStatusNameEnum.getOrderStatusEnum(orderInfo.getOrderStatus()));
        // 设置 payWayName 支付方式名称
        orderInfo.setPayWayName(PayWayEnumNameEnum.getPayWayName(orderInfo.getPayWay()));
        // 返回订单
        return orderInfo ;

    }
    /**
     * @description: 分页查询 获取用户订单
     * @author Petrichor
     * @date 2024/1/9 20:48
     * @param pageNum 当前页码
     * @param limit 每页记录数
     * @return 分页的订单数据
     **/
    @Override
    public IPage<OrderInfo> findUserPage(Long pageNum, Long limit) {
        Page<OrderInfo> page = new Page<>(pageNum,limit);
        // 获取用户id
        Long userId = AuthContextHolder.getUserId();
        IPage<OrderInfo> orderInfoIPage = orderInfoMapper.selectListByUserId(page,userId);
        return orderInfoIPage;
    }

    /**
     * @description: 更改订单状态为已支付
     * @author Petrichor
     * @date 2024/1/8 22:22
     * @param orderNo 订单号
     * @param orderStatus 订单状态
     * @return NULL
    **/
    private void updateOrderStatus(String orderNo, String orderStatus) {
        LambdaQueryWrapper<OrderInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(lambdaQueryWrapper);
        orderInfo.setOrderStatus(orderStatus);

        orderInfoMapper.updateById(orderInfo);
    }
}
